package com.job.client.common.utils;

import com.job.client.model.posts.pojo.Category;
import com.job.client.model.posts.vo.CategoryVo;

import java.util.ArrayList;
import java.util.List;

public class ListToChildrenUtils {
    public static List<CategoryVo> convertCategoriesToVo(List<Category> categories) {
        List<CategoryVo> categoryVoList = new ArrayList<>();
        for (Category category : categories) {
                CategoryVo categoryVo = new CategoryVo();
                categoryVo.setCategoryId(category.getCategoryId());
                categoryVo.setName(category.getName());
                categoryVo.setParentId(category.getParentId());
                categoryVo.setCreateTime(category.getCreateTime());
                categoryVo.setUpdateTime(category.getUpdateTime());
                categoryVoList.add(categoryVo);
        }
        for (CategoryVo categoryVo : categoryVoList) {
            if (categoryVo.getParentId() == null) {
                addChildren(categoryVo, categoryVoList);
            }
        }
        Integer size=0;
        for (Category category : categories) {
            if(category.getParentId()==null){
                size++;
            }
        }
        return categoryVoList.subList(0, size);
    }

    private static void addChildren(CategoryVo categoryVo, List<CategoryVo> categoryVoList) {
        for (CategoryVo child : categoryVoList) {
            if (child.getParentId() != null && child.getParentId().equals(categoryVo.getCategoryId())) {
                categoryVo.getChildren().add(child);
                addChildren(child, categoryVoList);
            }
        }
    }
}
